package com.dzm.thirdpart.service.impl;

import com.dzm.thirdpart.config.GiteeProperties;
import com.dzm.thirdpart.service.GiteeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 作者：Dzm
 * 时间：2024-09-14-12:38
 * 功能：
 */

@Service
public class GiteeServiceImpl implements GiteeService {

    @Autowired
    private GiteeProperties giteeProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Map<String, String> getUserInfo(String code) {
        //通过code获取token
        String tokenUrl = String.format("https://gitee.com/oauth/token?grant_type=%s&code=%s&client_id=%s&redirect_uri=%s&client_secret=%s",
                giteeProperties.getGrantType(),
                code,
                giteeProperties.getClientId(),
                giteeProperties.getRedirectUri(),
                giteeProperties.getClientSecret());

        Map<String, String> map = restTemplate.postForObject(tokenUrl, null, Map.class);
        String accessToken = map.get("access_token");

        //根据token获取用户信息
        String userUrl = String.format("https://gitee.com/api/v5/user?access_token=%s", accessToken);
        Map<String, String> userInfo = restTemplate.getForObject(userUrl, Map.class);

        return userInfo;
    }
}
